import { defineComponent, ref, reactive, inject } from 'vue'
import type { Ref } from 'vue'
import { useFullscreen } from '@vueuse/core'
import type { FormInst, FormRules } from 'naive-ui'
import {
  NButton,
  useMessage,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NScrollbar
} from 'naive-ui'
import rankApi from '@/service/api/yang/operation/rank'
import pageStyle from '@/theme/common.module.scss'
import MacHeader from '@/components/codeBlock/MacHeader'
import YQuil from '@/components/yang/YQuil'
import systemType from '@/enum/systemType'
interface formState {
  id?: number
  type: string
  xpKey: string
  label: string
  value: string
}
interface editState {
  show: boolean
  title: string
  queryForm: formState
}
export default defineComponent({
  emits: ['success'],
  setup(_, { emit, expose }) {
    const $clone = inject('$clone') as <T>(data: T) => T
    const modalRef: Ref<any> = ref()
    const { isFullscreen, toggle }: { isFullscreen: Ref<boolean>; toggle: () => Promise<void> } =
      useFullscreen(modalRef)
    const toast = useMessage()

    const initForm: formState = {
      type: 'TEXT',
      xpKey: '',
      label: '',
      value: ''
    }
    const state: editState = reactive({
      show: false,
      title: '添加',
      queryForm: $clone(initForm)
    })
    const rules: FormRules = {
      type: [
        {
          required: true,
          message: '请选择类型',
          trigger: 'blur'
        }
      ],
      xpKey: [
        {
          required: true,
          message: '请输入唯一标识',
          trigger: 'blur'
        }
      ],
      label: [
        {
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }
      ],
      value: [
        {
          required: true,
          message: '请输入内容',
          trigger: 'blur'
        }
      ]
    }
    const formRef = ref<FormInst | null>(null)
    const handleValidateClick = (e: MouseEvent): void => {
      e.preventDefault()
      formRef.value?.validate((errors: any): void => {
        if (!errors) {
          save()
        }
      })
    }

    const save = async (): Promise<void> => {
      const params: formState = $clone(state.queryForm)
      if (params?.id) {
        const { code, message } = await rankApi.edit(params)
        if (code !== 200) {
          toast.error(message)
          return
        }
        toast.success('编辑成功')
      } else {
        const { code, message } = await rankApi.add(params)
        if (code !== 200) {
          toast.error(message)
          return
        }
        toast.success('添加成功')
      }
      emit('success')
      close()
    }
    const close = (): void => {
      state.queryForm = $clone(initForm)
      state.show = false
    }

    const open = (row?: any): void => {
      state.title = '添加'
      if (row) {
        state.queryForm = $clone(row)
        state.title = row?.id ? '编辑' : '添加'
      }
      state.show = true
    }

    expose({
      open
    })
    return () => (
      <NModal show={state.show} onUpdateShow={close} style-={{ paddingRight: 0 }}>
        <div ref={modalRef} class={pageStyle.modalEdit} style={{ width: '800px' }}>
          <MacHeader
            title={state.title}
            is-fullscreen={isFullscreen.value}
            show-desc={false}
            onToggle={toggle}
            onClose={close}
          />
          <div class="content">
            <NScrollbar style={{ maxHeight: '80vh', paddingRight: '10px' }}>
              <NForm ref={formRef} model={state.queryForm} rules={rules}>
                <NFormItem label="类型" path="type">
                  <NSelect v-model:value={state.queryForm.type} options={systemType} />
                </NFormItem>
                <NFormItem label="唯一标识" path="xpKey">
                  <NInput v-model:value={state.queryForm.xpKey} placeholder="请输入" />
                </NFormItem>
                <NFormItem label="标题" path="label">
                  <NInput v-model:value={state.queryForm.label} placeholder="请输入" />
                </NFormItem>
                <NFormItem label="内容" path="value">
                  {state.queryForm.type === 'RICH' ? (
                    <YQuil v-model={state.queryForm.value} />
                  ) : (
                    <NInput v-model:value={state.queryForm.value} placeholder="请输入" />
                  )}
                </NFormItem>
                <NFormItem>
                  <div class="w-full flex justify-end">
                    <NButton type="primary" attr-type="button" onClick={handleValidateClick}>
                      <span>提交</span>
                    </NButton>
                  </div>
                </NFormItem>
              </NForm>
            </NScrollbar>
          </div>
        </div>
      </NModal>
    )
  }
})
